package com.sinbader.xiaole.common.utils;


import java.io.*;
import java.util.logging.Logger;


/**
 * JAVA序列化及反序列化工具类
 * 
 * @author Administrator
 * @param <M> 类
 * @version 1.0
 */
public class SerializeUtil<M extends Serializable> {
    private static final Logger LOGGER = Logger.getLogger(SerializeUtil.class.getName());

    /**
     * 主要功能:序列化对象到byte数组
     * 注意事项:无
     * 
     * @param value 带序列号对象
     * @return byte数组
     */
    @SuppressWarnings("unchecked")
    public byte[] serialize(Object value) {
        if (value == null) {
            throw new NullPointerException("Can't serialize null");
        }
        byte[] result = null;
        ByteArrayOutputStream bos = null;
        ObjectOutputStream os = null;
        try {
            bos = new ByteArrayOutputStream();
            os = new ObjectOutputStream(bos);
            M m = (M)value;
            os.writeObject(m);
            os.close();
            bos.close();
            result = bos.toByteArray();
        } catch (IOException e) {
            throw new IllegalArgumentException("Non-serializable object", e);
        } finally {
            close(os);
            close(bos);
        }
        return result;
    }

    /**
     * 主要功能:反序列化
     * 注意事项:无
     * 
     * @param in 序列化数组
     * @return 对象
     */
    @SuppressWarnings("unchecked")
    public M deserialize(byte[] in) {
        M result = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream is = null;
        try {
            if (in != null) {
                bis = new ByteArrayInputStream(in);
                is = new ObjectInputStream(bis);
                result = (M)is.readObject();
                is.close();
                bis.close();
            }
        } catch (IOException e) {
            LOGGER.info("Caught IOException decoding bytes of data");
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            LOGGER.info("Caught CNFE decoding bytes of data");
        } finally {
            close(is);
            close(bis);
        }
        return result;
    }

    /**
     * 主要功能:Closeable 关闭
     * 注意事项:无
     * 
     * @param closeable closeable
     */
    public void close(Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (Exception e) {
                LOGGER.info("Unable to close " + closeable);
            }
        }
    }
}
